#!/bin/bash

repo="$(           echo "$1" | python -c 'import sys; x=sys.stdin.read(); y=x.split("/"); print(y[1] if len(y) >= 2 else x)')"
github_username="$(echo "$1" | python -c 'import sys; x=sys.stdin.read(); y=x.split("/"); print(y[0] if len(y) >= 2 else "")')"
branch="${2:-master}"
subfolder="$3"

if [[ -z "$subfolder" ]]; then
  subfolder="$repo"
fi

if [[ -z "$github_username" ]] || [[ -z "$repo" ]] || [[ -z "$branch" ]] || [[ -z "$subfolder" ]]; then
  echo "github-subtree-create <github_username>/<repo_name> <branch> <subfolder>"
  echo ""
  echo " Clones that branch of their repo into <repo_name>/ as a git subtree"
  echo ""
  echo " Branch defaults to master"
  echo " Subfolder defaults to <repo_name>"
  echo ""
  echo "Examples:"
  echo ""
  echo "    github-subtree-create foouser/bar"
  echo "    github-subtree-create foouser/bar devbranch"
  echo "    github-subtree-create foouser/bar devbranch bar_goes_here/"
  echo ""
  exit 1
fi

echo ""
cat <<EOF
mkdir -p "${subfolder}"
EOF
mkdir -p "${subfolder}"

remote="${github_username}/${repo}"
echo ""
cat <<EOF
git remote add -f "${remote}" "https://github.com/${github_username}/${repo}"
EOF
git remote add -f "${remote}" "https://github.com/${github_username}/${repo}"


echo ""
cat <<EOF
git merge -s ours --no-commit "${remote}/${branch}"
EOF
git merge -s ours --no-commit "${remote}/${branch}"

echo ""
cat <<EOF
git read-tree --prefix="${subfolder}/" -u "${remote}/${branch}"
EOF
git read-tree --prefix="${subfolder}/" -u "${remote}/${branch}"

echo ""
echo "Merged ${github_username}/${repo}/${branch} into ${subfolder}/ as a subtree."
echo "Commit or undo the changes."
echo ""

